package com.cl.ks.utils;

import java.util.ArrayList;
import java.util.List;

public class ExceptionUtil {
    public static String getExceptionChainAsString(Throwable t) {
        StringBuilder sb = new StringBuilder();
        appendExceptionChain(t, sb);
        return sb.toString();
    }

    private static void appendExceptionChain(Throwable t, StringBuilder sb) {
        sb.append("Exception Class: ").append(t.getClass().getName()).append("\n");
        sb.append("Exception Message: ").append(t.getMessage()).append("\n");

        List<StackTraceElement> filteredStackTrace = filterStackTrace(t.getStackTrace());
        if (!filteredStackTrace.isEmpty()) {
            sb.append("Stack Trace:\n");
            for (StackTraceElement element : filteredStackTrace) {
                sb.append("\tat ").append(element).append("\n");
            }
        }

        Throwable cause = t.getCause();
        if (cause != null) {
            sb.append("Caused by:\n");
            appendExceptionChain(cause, sb); // 递归调用
        } else {
            sb.append("End of exception chain.\n");
        }
    }

    private static List<StackTraceElement> filterStackTrace(StackTraceElement[] stackTrace) {
        List<StackTraceElement> filteredStackTrace = new ArrayList<>();
        for (StackTraceElement element : stackTrace) {
            if (shouldInclude(element)) {
                filteredStackTrace.add(element);
            }
        }
        return filteredStackTrace;
    }

    private static boolean shouldInclude(StackTraceElement element) {
        // 过滤掉非 com.cl 包的堆栈跟踪行
        return element.getClassName().startsWith("com.cl");
    }
}
